package cn.b.sky.common.utils.facade;

import cn.b.sky.common.utils.FTPUtils;
import cn.b.sky.common.utils.SkyFileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Component("ftpUtils")
public class FTPUtilsFacade implements FTPUtils {
  private static final Logger log = LoggerFactory.getLogger(FTPUtilsFacade.class);

  private FTPClient ftpClient;

  @Value("${ftp.servername}")
  private String servername;
  @Value("${ftp.port}")
  private Integer port;
  @Value("${ftp.username}")
  private String username;

  @Value("${ftp.password}")
  private String password;
  @Value("${ftp.path}")
  private String path = "/";

  private String encoding = "UTF-8";

  private Integer bufferSize = 3072;

  @Override
  public boolean connectToTheService() {
    boolean result = false;
    if (null == ftpClient) {
      ftpClient = new FTPClient();
    }
    try {
      ftpClient.connect(servername, port);
      FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
      conf.setServerLanguageCode("zh");
      ftpClient.configure(conf);
      //被动传输
      ftpClient.enterLocalPassiveMode();
      ftpClient.login(username, password);
      if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
        ftpClient.disconnect();
        return result;
      }
      // 设置文件操作目录
      result = ftpClient.makeDirectory(path);
      result = ftpClient.changeWorkingDirectory(path);
      // 设置文件类型 二进制
      result = ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
      // 设置缓冲器
      ftpClient.setBufferSize(bufferSize);
      // 设置编码
      ftpClient.setControlEncoding(encoding);
    } catch (Exception e) {
      log.error("{}", e);
    }
    return result;
  }

  /**
   * <strong>Title : uploadMultipartFiles<br></strong>
   * <strong>Description : </strong>springmvc 上传文件<br> 
   * <strong>Create on : 2016-7-26 上午10:04:56<br></strong>
   * <p>
   * @param file 文件
   * @param filePath 文件路径
   * @param fileName 文件名称
   * @return
   * @see cn.b.sky.common.utils.FTPUtils#uploadMultipartFiles(org.springframework.web.multipart.MultipartFile, String, String)
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @Override
  public String uploadMultipartFiles(MultipartFile file, String filePath, String fileName) {
    try {
      return uploadInputStream(file.getInputStream(), filePath, fileName);
    } catch (IOException e) {
      log.error("{}", e);
      return null;
    }
  }

  @Override
  public String uploadInputStream(InputStream in, String filePath, String fileName) {
    boolean result = false;
    result = this.connectToTheService();
    if (result) {
      try {
        mkSavePath(filePath, 0);
        ftpClient.storeFile(fileName, in);
      } catch (IOException e) {
        log.error("{}", e);
      } finally {
        if (null != in) {
          try {
            in.close();
          } catch (IOException e) {
            log.error("{}", e);
          }
        }
        //disConenctToServer();

      }
      // 存储路径 业务/日期/文件名
      return filePath + fileName;
    }
    return null;
  }

  /**
   * 
   * <strong>Title : uploadCommonFiles<br>
   * </strong> <strong>Description : </strong>上传普通文件<br>
   * <strong>Create on : 2015-10-8 上午9:30:23<br>
   * </strong>
   * <p>
   * 
   * @param file
   *             void
   * @throws
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   *          <strong>修改历史:</strong><br>
   *          修改人 | 修改日期 | 修改描述<br>
   *          -------------------------------------------<br>
   * <br>
   * <br>
   * @throws IOException 
   */
  @Override
  public String uploadCommonFiles(File file, String bussiness, String fileName) throws IOException {
    boolean result = this.connectToTheService();
    if (!result) {
      return null;
    }
    /*
     * if(file.isDirectory()){ ftpClient.makeDirectory(file.getName());
     * ftpClient.changeWorkingDirectory(file.getName()); String[] files =
     * file.list(); for (int i = 0; i < files.length; i++) { File file1 =
     * new File(file.getPath()+"\\"+files[i] ); if(file1.isDirectory()){
     * uploadCommonFiles(file1); ftpClient.changeToParentDirectory(); }else{
     * File file2 = new File(file.getPath()+"\\"+files[i]); FileInputStream
     * input = new FileInputStream(file2);
     * ftpClient.storeFile(file2.getName(), input); input.close(); } }
     * }else{
     */
    File file2 = new File(file.getPath());
    FileInputStream input = new FileInputStream(file2);
    fileName = SkyFileUtils.renameFileName(file.getName(), fileName);
    String filePath = SkyFileUtils.buildFilePath(bussiness);
    mkSavePath(filePath, 0);
    ftpClient.storeFile(fileName, input);

    input.close();
    return filePath;
    /* } */
  }

  /**
   * 
   * <strong>Title : deleteFile<br></strong>
   * <strong>Description : </strong>删除附件,如果附件名为空，则folderpath是路径+文件名，直接删除<br> 
   * <strong>Create on : 2015-10-8 下午12:21:29<br></strong>
   * <p>
   * @param folderpath
   * void
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @Override
  public void deleteFile(String folderpath) {
    this.connectToTheService();
    try {
      ftpClient.deleteFile(folderpath);
    } catch (IOException e) {
      log.error("{}", e);
    } finally {
      disConenctToServer();
    }

  }

  @Override
  public Boolean isExistisFile(String filePath, String fileName) throws IOException {
    if (StringUtils.isBlank(fileName)) {
      return false;
    }
    this.connectToTheService();
    FTPFile[] fs = ftpClient.listFiles(path + filePath);
    for (FTPFile ff : fs) {
      if (ff.isFile() && fileName.equals(ff.getName())) {
        return true;
      }
    }
    return false;
  }

  /**
   * 
   * <strong>Title : fileDownload<br></strong>
   * <strong>Description : </strong>ftp 下载， 指定下载ftp上某一个目录或者文件到本地<br> 
   * <strong>Create on : 2015-10-8 下午12:29:24<br></strong>
   * <p>
   * @param filePath
   * @param os
   * @return boolean
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @Override
  public boolean fileDownload(String filePath, OutputStream os) {
    this.connectToTheService();
    try {

      ftpClient.retrieveFile(filePath, os);
      return true;
    } catch (IOException e) {
      log.error("{}", e);
      return false;
    } finally {
      disConenctToServer();
    }
  }

  /**
   * <strong>Title : disConenctToServer<br></strong>
   * <strong>Description : </strong>关闭连接,单例的不需要关闭<br> 
   * <strong>Create on : 2015-10-8 下午12:27:41<br></strong>
   * <p>
   * void
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  private void disConenctToServer() {
    if (ftpClient.isConnected()) {
      try {
        ftpClient.logout();
        ftpClient.disconnect();
      } catch (IOException e) {
        log.error("{}", e);
      }
    }

  }

  private void mkSavePath(String folderpath, Integer flag) {
    if (null != ftpClient) {
      try {
        for (String folder : folderpath.split("/")) {
          //0表示上传
          if (flag == 0) {
            ftpClient.makeDirectory(folder);
          }
          ftpClient.changeWorkingDirectory(folder);
        }
      } catch (IOException e) {
        log.error("{}", e);
      }
    }
  }

  public FTPClient getFtpClient() {
    return ftpClient;
  }

  public void setFtpClient(FTPClient ftpClient) {
    this.ftpClient = ftpClient;
  }

  public String getServername() {
    return servername;
  }

  public void setServername(String servername) {
    this.servername = servername;
  }

  public Integer getPort() {
    return port;
  }

  public void setPort(Integer port) {
    this.port = port;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getPath() {
    return path;
  }

  public void setPath(String path) {
    this.path = path;
  }

  public String getEncoding() {
    return encoding;
  }

  public void setEncoding(String encoding) {
    this.encoding = encoding;
  }

  public Integer getBufferSize() {
    return bufferSize;
  }

  public void setBufferSize(Integer bufferSize) {
    this.bufferSize = bufferSize;
  }

  public static void main(String[] args) throws FileNotFoundException{
    FTPUtilsFacade facade = new FTPUtilsFacade();
    facade.setServername("124.222.11.25");
    facade.setPort(1212);
    facade.setPath("mes/");
    facade.setUsername("ftp_user");
    facade.setPassword("mes@ftp123456");
    File file = new File("/Users/lidapeng/Documents/云堤/2023-OKR/Q1.xlsx");
    InputStream fileIn = new FileInputStream(file);
    facade.uploadInputStream(fileIn,"equipment/2023-08-09/","52101ae0-3ec6-42b4-99bf-9ac77f78cbd9.jpeg");
  }
}
